package com.maven.front.service.frontLogin;

import com.maven.front.bean.EduUser;
import com.maven.front.bean.Result;
import com.maven.front.mapper.EduUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;


@Service
@Slf4j
public class LoginService {


    @Resource
    private EduUserMapper eduUserMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     *  用户注册
     * @param eduUser
     * @return
     */
    public Result save(EduUser eduUser){
        int num =  eduUserMapper.insertSelective(eduUser);
        if(num>0){
            return new Result(200,"注册成功!");
        }
        return new Result(250,"注册失败");
    }

    /**
     * 查询用户
     * @param id
     * @return
     */
    public Result getById(int id){
        EduUser eduUser = (EduUser) redisTemplate.opsForValue().get(id+"EduUser");

        if(ObjectUtils.isEmpty(eduUser)){
            eduUser = eduUserMapper.selectByPrimaryKey(id);
            if(ObjectUtils.isEmpty(eduUser)){
                return new Result(251,"查询失败");
            }else{
                redisTemplate.opsForValue().set(id+"EduUser",eduUser);
                redisTemplate.expire(id+"EduUser",15, TimeUnit.MINUTES);
            }
        }
//        EduUser eduUser = eduUserMapper.selectByPrimaryKey(id);
//        log.info("******"+eduUser);
        return new Result(200,"查询成功",eduUser);
    }

    /**
     * 登录验证
     * @param email
     * @param password
     * @return
     */
    public Result check(String email,String password){
        EduUser eduUser = eduUserMapper.check(email,password);
        if(ObjectUtils.isEmpty(eduUser)){
            return new Result(252,"账号或密码错误");
        }
        return new Result(200,"查询成功",eduUser);
    }


}
